package com.example.springblog.controller;

import com.example.springblog.Utils.JWTUtils;
import com.example.springblog.constant.Constants;
import com.example.springblog.model.BlogInfo;
import com.example.springblog.service.BlogService;
import io.jsonwebtoken.lang.Strings;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @RequestMapping(value = "getList",method = RequestMethod.GET)
    public List<BlogInfo> getList(){
        return blogService.getList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId , HttpServletRequest request){
        BlogInfo blogInfo = blogService.getBlogDetail(blogId);
        blogInfo.setLoginUser(false);
        //这里进行判断登录用户是否是文章作者
        String token = request.getHeader(Constants.USER_TOKEN_HEADER);
        //解析
        Integer userId = JWTUtils.getIDByToken(token);
        if(userId!=null && userId == blogInfo.getUserId()){
            blogInfo.setLoginUser(true);
        }
        return blogInfo;

    }

    /**
     * 添加博客
     */
    @RequestMapping("/add")
    //使用json进行数据的接收
    public boolean add(@RequestBody BlogInfo blogInfo, HttpServletRequest request){
        //进行参数的校验
        if(!Strings.hasLength(blogInfo.getTitle()) || !Strings.hasLength(blogInfo.getContent())){
            return false;
        }
        //从token中解析
        String token = request.getHeader(Constants.USER_TOKEN_HEADER);

        Integer id = JWTUtils.getIDByToken(token);
        blogInfo.setUserId(id);
        boolean result = blogService.insert(blogInfo);
        return result;
    }
    /**
     * 删除博客
     */
    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        //这里使用的就是逻辑删除
        BlogInfo blogInfo = new BlogInfo();

        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);

        Integer reault = blogService.delete(blogInfo);
        if(reault == 1){
            return true;
        }
        return false;
    }
    /**
     * 更新博客
     */
    @RequestMapping("updata")
    public boolean updata(BlogInfo blogInfo){
        if(!Strings.hasLength(blogInfo.getTitle())
                || !Strings.hasLength(blogInfo.getContent())
                ||  blogInfo.getId() == null){
            return false;
        }
        Integer result = blogService.updata(blogInfo);
        if(result == 1){
            return true;
        }
        return false;
    }

}
